﻿using System;
using ShpMerger;
using System.Threading;
using System.Collections.Generic;

namespace ShpMergerGUI
{
    internal class FileMeger
    {
        private DestFileWriter destFileWriter;
        private string destFile;
        private List<string> srcFiles;
        private int mergeCount;
        private bool puase;
        private bool stop;

        public event EventHandler<EventArgs> Merging;
        public event EventHandler<EventArgs> Merged;

        private void MergeByThread()
        {
            while (!puase && mergeCount < srcFiles.Count)
            {
                OnMerging();
                destFileWriter.AddSrcFile(srcFiles[mergeCount], destFile);
                ++mergeCount;
            }
            if (mergeCount == srcFiles.Count && stop == false)
            {
                stop = true;
                OnMerged();
            }
        }

        protected virtual void OnMerging()
        {
            Merging(this, new EventArgs());
        }

        protected virtual void OnMerged()
        {
            Merged(this, new EventArgs());
        }

        public FileMeger()
        {
            destFileWriter = new DestFileWriter();
            srcFiles = new List<string>();
            puase = false;
            stop = true;
            mergeCount = 0;
        }

        public void StartMerge(List<string> srcFiles, string destFile)
        {
            this.destFile = destFile;
            this.srcFiles = srcFiles;
            mergeCount = 0;
            puase = false;
            stop = false;
            destFileWriter.InitDestFile(destFile);
            new Thread(MergeByThread).Start();
        }

        public void PuaseMerge()
        {
            puase = true;
        }

        /// <summary>
        /// go on merge
        /// </summary>
        public void ReStartMerge()
        {
            puase = false;
            new Thread(MergeByThread).Start();
        }

        public void StopMerge()
        {
            puase = true;
            stop = true;
            OnMerged();
        }

        /// <summary>
        /// get current merged src file
        /// </summary>
        /// <returns></returns>
        public string GetMergingFile()
        {
            return srcFiles[mergeCount];
        }

        /// <summary>
        /// get current merge percent
        /// </summary>
        /// <returns></returns>
        public int GetMergePercent()
        {
            return mergeCount / srcFiles.Count * 100;
        }
    }
}
